package com.geek.factory.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.geek.factory.dto.MaterialUsageDTO;
import com.geek.factory.entity.Material;
import com.geek.factory.mapper.MaterialMapper;
import com.geek.factory.service.IMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

@Service
@Slf4j
public class MaterialServiceImpl extends ServiceImpl<MaterialMapper, Material> implements IMaterialService {
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deductMaterialStock(List<MaterialUsageDTO> materials) {
        for (MaterialUsageDTO item : materials) {
            Material material = this.getById(item.getMaterialId());
            if (material == null) {
                throw new RuntimeException("原料不存在: ID=" + item.getMaterialId());
            }
            if (material.getQuantity().compareTo(item.getRequiredQuantity()) < 0) {
                throw new RuntimeException("原料 " + material.getMaterialName() + " 库存不足");
            }

            // 库存扣减
            material.setQuantity(material.getQuantity().subtract(item.getRequiredQuantity()));
            this.updateById(material);
        }
    }


    private static final String CACHE_NAME = "material";

//    @Override
//    @Cacheable(value = CACHE_NAME, key = "#id")
//    public Material getById(Serializable id) {
//        log.info("从数据库查询原料信息, id: {}", id);
//        return super.getById(id);
//    }
@Override
@Cacheable(value = CACHE_NAME, key = "#id", unless = "#result == null")
public Material getById(Serializable id) {
    log.info("从数据库查询原料信息, id: {}", id);
    return super.getById(id);
}

    @Override
    @CachePut(value = CACHE_NAME, key = "#material.materialId")
    public boolean save(Material material) {
        boolean result = super.save(material);
        log.info("新增原料信息并写入缓存, id: {}, result: {}", material.getMaterialId(), result);
        return result;
    }

    @Override
    @CachePut(value = CACHE_NAME, key = "#material.materialId")
    public boolean updateById(Material material) {
        boolean result = super.updateById(material);
        log.info("更新原料信息并更新缓存, id: {}, result: {}", material.getMaterialId(), result);
        return result;
    }

    @Override
    @CacheEvict(value = CACHE_NAME, key = "#id")
    public boolean removeById(Serializable id) {
        boolean result = super.removeById(id);
        log.info("删除原料信息并删除缓存, id: {}, result: {}", id, result);
        return result;
    }
}
